package com.yunglu.pa03;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.os.AsyncTask;

class GetRTTTask extends TimerTask {
	private String hostName;
	private int portNumber;
	DelayView dlview;

	public GetRTTTask(String hn, int pn, DelayView dv) {
		hostName = hn;
		portNumber = pn;
		dlview = dv;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		long startTime = System.currentTimeMillis();
		Socket sock;
		BufferedWriter bufwriter;
		BufferedReader bufreader;
		try {
			sock = new Socket(hostName, portNumber);
			InputStream instm = sock.getInputStream();
			InputStreamReader inrd = new InputStreamReader(instm);
			bufreader = new BufferedReader(inrd);
			OutputStream outstm = sock.getOutputStream();
			OutputStreamWriter outwr = new OutputStreamWriter(outstm);
			bufwriter = new BufferedWriter(outwr);
			Random rd = new Random(System.currentTimeMillis());
			String outmsg = String.valueOf(rd.nextInt()) + "\n";
			// remember to add "\n" because the server expects it
			bufwriter.write(outmsg);
			bufwriter.flush();
			String inmsg = bufreader.readLine();
			sock.close();
			long endTime = System.currentTimeMillis();
			dlview.updateValue((int) (endTime - startTime));
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

public class NetworkTask extends AsyncTask<String, Void, Void> {
	public static final int TIMER_INTERVAL = 1000;
	// 1000 millisecondsone = 1 second
	private Timer periodicTimer;
	private DelayView dlview;

	public NetworkTask(DelayView dv) {
		periodicTimer = new Timer();
		dlview = dv;
	}

	@Override
	protected Void doInBackground(String... params) {
		// TODO Auto-generated method stub
		TimerTask tt = new GetRTTTask(params[0], Integer.parseInt(params[1]),
				dlview);
		periodicTimer.scheduleAtFixedRate(tt, 0, TIMER_INTERVAL);
		return null;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onCancelled()
	 */
	@Override
	protected void onCancelled() {
		// TODO Auto-generated method stub
		super.onCancelled();
		periodicTimer.cancel();
	}

}
